package com.nickstumpos.android.easyVolume.scheduler.reciever;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import com.nickstumpos.android.easyVolume.constants.EVCONSTANTS;
import com.nickstumpos.android.easyVolume.preset.service.PresetService;
import com.nickstumpos.android.easyVolume.scheduler.dto.SchedulingInfoDto;
import com.nickstumpos.android.easyVolume.scheduler.util.SchedulingUtil;

public class ApplyPresetReciever extends BroadcastReceiver {

	private Context						context;
	private SchedulingInfoDto	schedule;
	private PresetService			presetService;

	@Override
	public void onReceive(Context context, Intent intent) {
		this.context = context;
		this.presetService = new PresetService(context);
		this.schedule = (SchedulingInfoDto) intent
				.getSerializableExtra(EVCONSTANTS.SCHEDULE);
		if (this.schedule.isRepeating()) {
			this.scheduleNextRun();
		}
		this.presetService.applyPreset(this.schedule.getPreset());
	}

	private void scheduleNextRun() {
		Intent intent = new Intent(this.context, ApplyPresetReciever.class);
		intent.putExtra(EVCONSTANTS.SCHEDULE, this.schedule);
		PendingIntent presetSender = PendingIntent.getBroadcast(this.context,
				this.schedule.getCode(), intent, 0);
		AlarmManager am = (AlarmManager) this.context
				.getSystemService(Context.ALARM_SERVICE);
		am.set(AlarmManager.RTC_WAKEUP, SchedulingUtil
				.findNextRunTime(this.schedule), presetSender);
	}

}
